package com.example.pro5_webflux_r2dbc_book.service;

import com.example.pro5_webflux_r2dbc_book.dao.BookDao;
import com.example.pro5_webflux_r2dbc_book.model.Book;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@Service
public class BookServiceImpl implements BookService {

    private final BookDao bookDao;

    public BookServiceImpl(BookDao bookDao) {
        this.bookDao = bookDao;
    }

    public Mono<Book> addBook(Book book) {
        return bookDao.save(book);
    }

    public Flux<Book> getAllBooks() {
        return bookDao.findAll();
    }

    public Mono<Book> getBookById(Long id) {
        return bookDao.findById(id);
    }

    public Mono<Book> updateBook(Long id, Book book) {
        return bookDao.findById(id)
                .flatMap(existingBook -> {
                    existingBook.setTitle(book.getTitle());
                    existingBook.setAuthor(book.getAuthor());
                    existingBook.setPrice(book.getPrice());
                    return bookDao.save(existingBook);
                });
    }

    public Mono<Void> deleteBook(Long id) {
        return bookDao.deleteById(id);
    }
}

